<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\batch\kuaishou;

use app\model\KsBidTaskContentModel;
use app\model\KsBidTaskModel;
use think\Exception;

trait UnitBidTrait
{
    /**
     * 更新组出价状态.
     */
    protected function unitBidFinish(): bool
    {
        if (! $this->taskModel instanceof KsBidTaskModel || ! $this->taskModel->getKey()) {
            return self::setError('未知组出价修改');
        }

        if (! $this->taskModel->getAttr('is_pull')) {
            return true;
        }

        try {
            $waitNum = (new KsBidTaskContentModel())->where([
                ['task_id', '=', $this->taskModel->getKey()],
                ['status', '=', KsBidTaskContentModel::STATUS_WAIT],
            ])->count();
            if (! $waitNum) {
                $num = (new KsBidTaskContentModel())->where('task_id', $this->taskModel->getKey())->count();
                $fallNum = (new KsBidTaskContentModel())->where([
                    ['task_id', '=', $this->taskModel->getKey()],
                    ['status', '=', KsBidTaskContentModel::STATUS_FAIL],
                ])->count();

                $this->taskModel->setAttrs([
                    'num' => $num,
                    'status' => $fallNum > 0 ? (KsBidTaskModel::STATUS_FAIL) : (KsBidTaskModel::STATUS_SUCCESS),
                ]);

                if (! $this->taskModel->save()) {
                    throw new Exception('设置组出价任务状态失败');
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }
}
